package com.fuzongle.tank.service.impl;

import com.fuzongle.tank.base.BaseService;
import com.fuzongle.tank.base.JsonResult;
import com.fuzongle.tank.controller.PictureController;
import com.fuzongle.tank.dao.PictureDao;
import com.fuzongle.tank.entity.Picture;
import com.fuzongle.tank.service.PictureService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @Auther: fuzongle
 * @Date: 2020/6/12 23:34
 * @Description: 图片上传与下载 业务层实现类
 */
@Service
public class PictureServiceImpl extends BaseService implements PictureService {

    private static final Logger logger = LoggerFactory.getLogger(PictureController.class);

    @Autowired
    private PictureDao pictureDao;

    @Override
    public JsonResult selectList(Integer page, Integer size, String name) {
        PageHelper.startPage(page, size,getOrderBy("create_time","desc"));
        List<Picture> pictureList = pictureDao.selectList(name);
        PageInfo<Picture> pageInfo = new PageInfo<>(pictureList);
        return JsonResult.success(pageInfo.getTotal(),pageInfo.getList());
    }

    @Override
    public JsonResult insert(Picture picture) {
        int rows;
        picture.setCreateTime(new Date());
        rows = pictureDao.insert(picture);
        if (rows>0){
            return JsonResult.success();
        }
        return JsonResult.error();
    }

    @Override
    public void download(Integer id,HttpServletRequest request, HttpServletResponse response) throws Exception {

        String userAgent = request.getHeader("User-Agent");

         String filename="testIamge.jpg";
        //当文件名不是英文名的时候，最好使用url解码器去编码一下，
        filename= URLEncoder.encode(filename,"UTF-8");
        byte[] bytes = userAgent.contains("MSIE") ? filename.getBytes() : filename.getBytes("UTF-8");;

        filename = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
        //将响应的类型设置为图片
        response.reset();
        response.setContentType("image/jpg");
        response.setHeader("Content-Disposition", "attachment;filename=" + filename);
        response.setContentType("application/octet-stream; charset=UTF-8");
        //好了 ，现在通过IO流来传送数据
        InputStream input=request.getSession().getServletContext().getResourceAsStream("static\\picture\\PcStore/tank2076134641.19328607798.jpg");
        OutputStream output = response.getOutputStream();
        byte[]buff=new byte[1024*10];//可以自己 指定缓冲区的大小
        int len=0;
        while((len=input.read(buff))>-1)
        {
            output.write(buff,0,len);
        }
        //关闭输入输出流
        input.close();
        output.close();
    }

    @Override
    public JsonResult delete(Integer id) {
        int rows = 0;
        rows = pictureDao.delete(id);
        if ( rows > 0) {
            return  JsonResult.success();
        }
        return JsonResult.error();
    }

    public static final String[] IMAGE_EXTENSION = { "bmp", "gif", "jpg", "jpeg", "png" };

    @Override
    public JsonResult upload(MultipartFile multipartFile, HttpServletRequest request) {
        String realUploadPath = "";// 图片位置
        if (multipartFile == null){
            JsonResult.error("文件不能未空!");
        }
        //原文件
        String fileName = multipartFile.getOriginalFilename();
        //获取文件后缀
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        String ORDER_NO = "tank" + new SimpleDateFormat("yy").format(new Date())
                + String.valueOf(System.currentTimeMillis() / 1000).substring(7, 10)
                +(((Math.random() * 9 + 1) * 10000));
        String newName = ORDER_NO  + fileType;
        logger.info("最新图片名字{}",newName);
        realUploadPath = request.getSession().getServletContext().getRealPath("/") + "static\\picture\\PcStore/";
        String newPath = realUploadPath + newName;
        System.out.println("根据相对路径获取绝对路径，图片上传后位于元数据中" + realUploadPath);
        //上传位置
        File files= new File(newPath);
        if(!files.exists()) {
            files.mkdirs();
        }
        try {
            multipartFile.transferTo(files);
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
        }
        HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("data","static/picture/PcStore/"+newName);
        return  JsonResult.success(objectObjectHashMap);
    }


}